package it.win4buy.controller;

import it.win4buy.connectionpool.ConnectionPool;
import it.win4buy.datamodel.FlashDataModel;
import it.win4buy.datamodel.TableData;
import it.win4buy.datamodel.UserData;
import it.win4buy.util.Logger;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Vector;

public class GameController {

	private ConnectionPool connectionPool = null;
	private boolean debugMode = false;

	private FlashDataModel fdm = null;

	public GameController() {
		fdm = new FlashDataModel();

		if (System.getProperty("debugMode") != null) {
			if (System.getProperty("debugMode").equals("true")) {
				debugMode = true;
				Logger.log("Application started in debugMode");
			}

		}

		if (debugMode) {
			// DEBUG
			ConnectionPool.init("jdbc:mysql://localhost:3306/w4b_game", "root",
					"archimede", 10);

		} else {
			ConnectionPool.init("jdbc:mysql://localhost:3306/w4b_game",
					"admin", "archimede", 10);
		}

		try {
			connectionPool = ConnectionPool.getInstance();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		fdm.setUsersData(loadUserdata());
		fdm.setTablesData(loadTablesData());
	}

	private TableData[] loadTablesData() {

		Connection conn;
		PreparedStatement preparedStatement = null;
		Vector appo = new Vector();
		TableData[] ret = null;

		ResultSet rs = null;
		try {
			conn = connectionPool.getConnection();
			preparedStatement = conn
					.prepareStatement("select * from tavoli_gioco as tg ,categorie as cat,tipi_tavolo as tt "
							+ " where tg.tipo_tavolo = tt.id and tt.id_categoria=cat.idcategorie and stato_tavolo=1  ");

			rs = preparedStatement.executeQuery();
			int i = 0;
			while (rs.next()) {
				String tableId = rs.getString("tg.idtavolo_gioco");
				TableData tableData = new TableData();
				tableData.setAnswerTime(rs.getString("tt.min_risposta"));
				tableData.setBuyIn(rs.getString("tt.buy_iN"));
				tableData.setCategory(rs.getString("cat.descrizione"));
				tableData.setDifficultLevel(rs.getString("tt.LIV_DIFFICOLTA"));
				tableData.setFreeCredits(rs.getString("tt.crediti_free"));
				tableData.setGameDescription(rs.getString("tt.desc_giocata"));
				tableData.setGameType(rs.getString("tt.desc_tipo_gioco"));
				tableData.setMaxPlayers("" + rs.getShort("num_player"));
				tableData.setQuestionsNum(rs.getString("tt.num_domande"));
				tableData.setRegisteredPlayers(""
						+ getRegistrationCount(tableId));
				tableData.setSpeciality(rs.getString("tt.ID_SPECIALITA"));
				tableData.setTableId(tableId);
				tableData.setTornamentName(rs.getString("tt.desc_principale"));
				tableData.setWinningPlayer(rs.getString("tt.premiati"));
				appo.add(tableData);
				System.out.println("riga:" + i++);

			}
			ret = new TableData[appo.size()];
			appo.toArray(ret);

		} catch (Exception e) {
		} finally {
			try {
				rs.close();
				preparedStatement.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return ret;

	}

	/**
	 * 
	 * @param tableId
	 * @return
	 */
	private int getRegistrationCount(String tableId) {
		int ret = 0;
		Connection conn;
		try {
			conn = connectionPool.getConnection();
			PreparedStatement psReg = conn
					.prepareStatement("SELECT count(*) as num,id_tavolo FROM `w4b_game`.`storico_registrazioni` where  id_tavolo =? group by  id_tavolo");
			psReg.setString(1, tableId);
			ResultSet rs = psReg.executeQuery();
			if (rs.next())
				ret = rs.getInt("num");
			psReg.close();
			rs.close();
			connectionPool.releaseConnection(conn);
		} catch (Exception e) {

			e.printStackTrace();
		}

		// System.out.println("tableId:" + tableId + " ret:" + ret);

		return ret;

	}

	private UserData[] loadUserdata() {

		Vector appo = new Vector();
		UserData[] ret = null;
		String sqlStr = "select jos_users.id, jos_users.username,"
				+ "users_data.credits,users_data.free_credits from jos_users,"
				+ "users_data where jos_users.id=users_data.id_user";
		Connection conn = null;

		try {
			conn = connectionPool.getConnection();
			PreparedStatement preparedStatement = conn.prepareStatement(sqlStr);
			ResultSet rs = preparedStatement.executeQuery();

			UserData el = new UserData();
			while (rs.next()) {
				el.setCredits(rs.getString("credits"));
				el.setFreeCredits(rs.getString("free_credits"));
				el.setRegistered(false);
				el.setRegTable(-1);
				el.setUserId(rs.getString("id"));
				el.setUserName("username");
				appo.add(el);
			}
			preparedStatement.close();
			rs.close();
			ret = new UserData[appo.size()];
			for (int i = 0; i < appo.size(); i++) {
				ret[i] = (UserData) appo.elementAt(i);
				isRegistered(conn, ret[i]);
			}

		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			connectionPool.releaseConnection(conn);
		}
		return ret;

	}

	private void isRegistered(Connection conn, UserData el) {
		PreparedStatement preparedStatement = null;
		ResultSet rs = null;

		String sqlStr = "Select  * from storico_registrazioni,tavoli_gioco where "
				+ "storico_registrazioni.id_tavolo = tavoli_gioco.idTavolo_gioco and"
				+ " tavoli_gioco.stato_tavolo=1 and "
				+ "id_user= "
				+ el.getUserId();

		try {
			preparedStatement = conn.prepareStatement(sqlStr);

			rs = preparedStatement.executeQuery();
			if (rs.next()) {
				el.setRegTable(rs.getInt("storico_registrazioni.id_tavolo"));
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				if (preparedStatement != null)
					preparedStatement.close();
				if (rs != null)
					rs.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}

}
